package com.yylending.las.authority.password;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.*;
import butterknife.*;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.yyfax.common.tools.RegexUtil;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.*;
import com.yylending.las.R;
import com.yylending.las.authority.verifycode.VerifyCodeModel;
import com.yylending.las.authority.verifycode.VerifyCodePresenter;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.utils.CountDownTimerUtils;
import com.yylending.las.main.MainActivity;

/**
 * Created by Pengrf on 2016/11/2 14:27.
 *
 * @更新者 $Author$
 * @更新时间 2016/11/2
 */
public class ForgetPwdActivity extends BaseActivity implements VerifyCodePresenter.View, ResetPasswordPresenter.View {
	private final static String TAG = "ForgetPwdActivity";

	private final static int LOADER_ID_VERIFY = 1;
	private final static int LOADER_ID_RESET = 2;

	private final static String KEY_PHONE = "key_phone";

	@BindView(R.id.forget_delete_phone)
	ImageView mForgetDeletePhone;
	@BindView(R.id.forget_phone_number)
	EditText mForgetPhoneNumber;
	@BindView(R.id.forget_phone_item)
	RelativeLayout mForgetPhoneItem;
	@BindView(R.id.forget_password)
	EditText mForgetPassword;
	@BindView(R.id.forget_delete_pwd)
	ImageView mForgetDeletePwd;
	@BindView(R.id.password_visible_chb)
	CheckBox mPasswordVisibleChb;
	@BindView(R.id.forget_password_item)
	RelativeLayout mForgetPasswordItem;
	@BindView(R.id.forget_verification_code_ic)
	ImageView mForgetVerificationCodeIc;
	@BindView(R.id.forget_verification_code)
	EditText mForgetVerificationCode;
	@BindView(R.id.forget_time_down_tx)
	TextView mForgetTimeDownTx;
	@BindView(R.id.forget_delete_verification_code)
	ImageView mForgetDeleteVerificationCode;
	@BindView(R.id.forget_view)
	View mForgetView;
	@BindView(R.id.forget_verification_code_item)
	RelativeLayout mForgetVerificationCodeItem;
	@BindView(R.id.forget_submit_btn)
	Button mForgetSubmitBtn;
	@BindView(R.id.main_content)
	LinearLayout mMainContent;

	private String mPhone;
	private String mCode;
	/**
	 * 页面传递过来的手机号
	 */
	private String mParameterPhone;
	private CountDownTimerUtils mCountDownTimer;

	private VerifyCodePresenter mVerifyCodePresenter;
	private ResetPasswordPresenter mResetPasswordPresenter;

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_VERIFY:
				return new PresenterLoader<>(this, new VerifyCodePresenter.Generator());
			case LOADER_ID_RESET:
				return new PresenterLoader<>(this, new ResetPasswordPresenter.Generator());
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_VERIFY:
				mVerifyCodePresenter = (VerifyCodePresenter) data;
				mVerifyCodePresenter.attach(this);
				break;
			case LOADER_ID_RESET:
				mResetPasswordPresenter = (ResetPasswordPresenter) data;
				mResetPasswordPresenter.attach(this);
				break;
		}
	}

	public static void start(RxAppCompatActivity aty, String phone) {
		Intent intent = new Intent(aty, ForgetPwdActivity.class);
		intent.putExtra(KEY_PHONE, phone);
		aty.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_forget_password);
		ButterKnife.bind(this);
		mParameterPhone = getIntent().getStringExtra(KEY_PHONE);
		setTitle(R.string.forget_password);
		getSupportLoaderManager().initLoader(LOADER_ID_VERIFY, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_RESET, null, this);
		initView();
	}

	private void initView() {
		if(TextUtils.isEmpty(mParameterPhone) && !TextUtils.isEmpty(Global.LOGIN_ACCOUNT_NAME)) {
			mParameterPhone = Global.LOGIN_ACCOUNT_NAME;
		}
		if (!TextUtils.isEmpty(mParameterPhone)) {
			mForgetPhoneNumber.setText(mParameterPhone);
			mForgetPhoneNumber.setSelection(mParameterPhone.length());
			mForgetDeletePhone.setVisibility(View.VISIBLE);
		}
		mForgetPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
	}

	@Override
	protected void onDestroy() {
		getSupportLoaderManager().destroyLoader(LOADER_ID_VERIFY);
		getSupportLoaderManager().destroyLoader(LOADER_ID_RESET);
		super.onDestroy();
	}

	@Override
	protected void onBackBtnPressed() {
		super.onBackBtnPressed();

	}

	@OnTextChanged(value = R.id.forget_phone_number, callback = OnTextChanged.Callback.TEXT_CHANGED)
	public void onPhoneChanged(CharSequence s, int start, int before, int count) {
		mPhone = s.toString().trim();
		if (mPhone.length() != 0) {
			mForgetDeletePhone.setVisibility(View.VISIBLE);
		} else {
			mForgetDeletePhone.setVisibility(View.GONE);
		}
	}

	/**
	 * 输入密码时监听
	 */
	@OnTextChanged(value = R.id.forget_password, callback = OnTextChanged.Callback.TEXT_CHANGED)
	public void onPasswordChanged(CharSequence s, int start, int before, int count) {
		if (s.toString().trim().length() != 0) {
			mForgetDeletePwd.setVisibility(View.VISIBLE);
		} else {
			mForgetDeletePwd.setVisibility(View.GONE);
		}
	}

	@OnTextChanged(value = R.id.forget_verification_code, callback = OnTextChanged.Callback.TEXT_CHANGED)
	public void onVerifyCodeChanged(CharSequence s, int start, int before, int count) {
		if (s.toString().trim().length() > 0) {
			mForgetDeleteVerificationCode.setVisibility(View.VISIBLE);
		} else {
			mForgetDeleteVerificationCode.setVisibility(View.GONE);
		}
	}

	/**
	 * 密码可见CheckBox监听
	 */
	@OnCheckedChanged({R.id.password_visible_chb})
	public void onPasswordChecked(CompoundButton btn, boolean checked) {
		if(checked){
			mForgetPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
		}else{
			mForgetPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
		}
		mForgetPassword.setSelection(mForgetPassword.getText().length());
	}


	@Override
	public void resetPwdSuccess() {
		showToast(R.string.pwd_reset_success);
		YJKD.logout();
		MainActivity.start(this, true);
	}

	@Override
	public void resetPwdFail(String code, String msg) {
		showToast(msg);
		//验证码不正确时清空验证码
		if(Constants.CODE_100007.equals(code)) mForgetVerificationCode.setText("");
	}

	@Override
	public void resetPwdRetCode(String retCode) {
		StatService.onEventWithSingleAttribute(this, StatIDSet.EVENT_ID_FORGOT_PASSWORD,retCode);
	}

	@Override
	public void getVerifyCodeSuccess(String code) {
		dismissLoading();
		showToast(R.string.validate_code_sent);
		mCountDownTimer = new CountDownTimerUtils(mForgetTimeDownTx, 60000, 1000, getString(R.string.get_verification_code_again), getString(R.string.retry_count_down));
		mCountDownTimer.start();
	}

	@Override
	public void getVerifyCodeFail(String msg) {
		dismissLoading();
		mForgetTimeDownTx.setEnabled(true);
		showToast(msg);
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		switch (functionalCode) {
			case VerifyCodeModel.METHOD_GET_VERIFY_CODE:
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mForgetTimeDownTx.setEnabled(true);
					}
				});
				break;
		}
	}

	@OnClick({R.id.forget_delete_phone, R.id.forget_delete_pwd, R.id.forget_time_down_tx, R.id.forget_delete_verification_code, R.id.forget_submit_btn})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.forget_delete_phone:
				mForgetPhoneNumber.getText().clear();
				break;
			case R.id.forget_delete_pwd:
				mForgetPassword.getText().clear();
				break;
			case R.id.forget_time_down_tx:
				YJKD.hideInputWindow(this);
				if (TextUtils.isEmpty(mPhone)) {
					showToast(R.string.input_correct_phone);
				} else {
					boolean isCorrectNum = mPhone.length() < 11;
					if (!isCorrectNum) {
						mForgetTimeDownTx.setEnabled(false);
						showLoading(true);
						mVerifyCodePresenter.verificationCode(VerifyCodeModel.TYPE_TEXT, mPhone, VerifyCodeModel.OPERATION_RESET_PASSWORD, "60");
					} else {
						showToast(R.string.input_correct_phone);
					}
				}
				break;
			case R.id.forget_delete_verification_code:    //验证码删除按钮
				mForgetVerificationCode.getText().clear();
				break;
			case R.id.forget_submit_btn:
				YJKD.hideInputWindow(this);
				String newPwd = mForgetPassword.getText().toString().trim();
				mCode = mForgetVerificationCode.getText().toString().trim();
				// TODO: 2017/7/25 修改校验规则
				if (TextUtils.isEmpty(mPhone)) {
					showToast(getString(R.string.please_input_toast, getString(R.string.mobile_phone)));    //手机号不能为空
					return;
				}
				if (TextUtils.isEmpty(newPwd)) {
					showToast(getString(R.string.please_input_toast, getString(R.string.password)));    //密码不能为空
					return;
				}
				if (TextUtils.isEmpty(mCode)) {
					showToast(getString(R.string.please_input_toast, getString(R.string.verification_code)));    //验证码不能为空
					return;
				}
				//密码,确认密码纯数字或字母提示,长度错误也提示
				if (!RegexUtil.isRightPwd(newPwd) || newPwd.length() < 6) {
					showToast(R.string.please_set_right_password);
					return;
				}
				mResetPasswordPresenter.resetPassword(mPhone, newPwd, mCode);
				break;
		}
	}
}
